package com.white.FalseWorld;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.white.FalseWorld.fragment.FW_BottomFragement;
import com.white.FalseWorld.utils.GlideEngine;
import com.white.FalseWorld.utils.ShowDateOrTimePickerDialog;
import com.white.FalseWorld.widgets.AutoLinearLayout;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.List;

import it.sauronsoftware.ftp4j.FTPAbortedException;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferException;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPIllegalReplyException;

import static java.sql.DriverManager.getConnection;

public class CreateNewsActivity extends AppCompatActivity {

    private Button news_send;
    private TextView new_rq_text,new_sj_text;
    private LinearLayout new_url,new_rq_layout,new_sj_layout,new_szwz_layout,new_dz_layout;
    private AutoLinearLayout new_picture;
    private EditText new_text,new_url_text,new_szwz_text,new_dz_text;
    private ImageView new_url_img,img_select;
    private RadioGroup news_type_group;
    private RadioButton news_type_text,news_type_textAndpicture,news_type_url,news_type_textAndurl;


    String[] news_pictures_path=new String[9];
    String[] news_pictures_name=new String[9];
    int news_pictures_nums=0;
    String last_news_pictures_path="";
    String new_url_img_path,new_url_img_name,last_new_url_img_path;

    String user;

    private int pyq_type;

    FW_BottomFragement fw_bottomFragement=new FW_BottomFragement();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_create_news );
        user = getIntent().getStringExtra( "user" );
        ImmersionBar.with(this).init();//一键透明状态栏


        news_send=findViewById( R.id.news_send );
        new_rq_text=findViewById( R.id.new_rq_text );
        new_sj_text=findViewById( R.id.new_sj_text );
        new_url=findViewById( R.id.new_url );
        new_rq_layout=findViewById( R.id.new_rq_layout );
        new_sj_layout=findViewById( R.id.new_sj_layout );
        new_szwz_layout=findViewById( R.id.new_szwz_layout );
        new_picture=findViewById( R.id.new_picture );
        new_text=findViewById( R.id.new_text );
        new_url_text=findViewById( R.id.new_url_text );
        new_szwz_text=findViewById( R.id.new_szwz_text );
        new_url_img=findViewById( R.id.new_url_img );
        news_type_group=findViewById( R.id.news_type_group );
        news_type_text=findViewById( R.id.news_type_text );
        news_type_textAndpicture=findViewById( R.id.news_type_textAndpicture );
        news_type_url=findViewById( R.id.news_type_url );
        news_type_textAndurl=findViewById( R.id.news_type_textAndurl );
        img_select=findViewById( R.id.img_select );
        new_dz_layout=findViewById( R.id.new_dz_layout );
        new_dz_text=findViewById( R.id.new_dz_text );

        Calendar calendar=Calendar.getInstance();

        new_rq_layout.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShowDateOrTimePickerDialog.showDatePickerDialog( CreateNewsActivity.this,3,new_rq_text,calendar );
            }
        } );

        new_sj_layout.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShowDateOrTimePickerDialog.showTimePickerDialog( CreateNewsActivity.this,3,new_sj_text,calendar );
            }
        } );

        news_send.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int tf_rq=new_rq_text.getText().toString().length();
                int tf_sj=new_sj_text.getText().toString().length();
                int tf_dz=new_dz_text.getText().toString().length();
                if (tf_rq==0|tf_sj==0|tf_dz==0){
                    Toast.makeText( CreateNewsActivity.this,getString( R.string.text_null ),Toast.LENGTH_SHORT ).show();
                }else{
                    //插入数据
                    news_Createinsert_mysql(CreateNewsActivity.this);
                }

            }
        } );

        new_picture.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择多图片
                select_Manypicture(9,188);
            }
        } );

        new_url_img.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //选择一图片
                select_Onepicture(1,1);
            }
        } );

        //单选组件的监听事件，得到动态类型
        news_type_group.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if(R.id.news_type_text == i){
                    pyq_type=1;

                    new_text.setVisibility( View.VISIBLE );
                    new_picture.setVisibility( View.GONE );
                    new_url.setVisibility( View.GONE );
                }else if(R.id.news_type_textAndpicture == i){
                    pyq_type=2;

                    new_text.setVisibility( View.VISIBLE );
                    new_picture.setVisibility( View.VISIBLE );
                    new_url.setVisibility( View.GONE );
                }else if(R.id.news_type_url == i){
                    pyq_type=3;

                    new_url.setVisibility( View.VISIBLE );
                    new_text.setVisibility( View.GONE );
                    new_picture.setVisibility( View.GONE );
                }else if(R.id.news_type_textAndurl == i){
                    pyq_type=4;

                    new_text.setVisibility( View.VISIBLE );
                    new_url.setVisibility( View.VISIBLE );
                    new_picture.setVisibility( View.GONE );
                }
            }
        } );
        replaceFragment_bottom( fw_bottomFragement );
    }
    private void replaceFragment_bottom(FW_BottomFragement fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace( R.id.fw_bottomframe_create_news, fragment );
        fragmentTransaction.commit();

    }
    private void select_Manypicture(int maxSelectpictureNum,int ResultCode) {
        //多张图片选择器
        PictureSelector.create( this )
                .openGallery( PictureMimeType.ofImage() )
                .loadImageEngine( GlideEngine.createGlideEngine())
                .isWeChatStyle(true)//开启R.style.picture_WeChat_style样式
                .maxSelectNum(maxSelectpictureNum)//最大选择数量
                .compress(true)//是否压缩
                .previewImage(true)
                .previewEggs(true)//预览图片时是否增强左右滑动图片体验
                .forResult( ResultCode );
    }
    private void select_Onepicture(int maxSelectpictureNum,int ResultCode) {
        //一张图片选择器
        PictureSelector.create( this )
                .openGallery( PictureMimeType.ofImage() )
                .loadImageEngine( GlideEngine.createGlideEngine())
                .isWeChatStyle(true)//开启R.style.picture_WeChat_style样式
                .maxSelectNum(maxSelectpictureNum)//最大选择数量
                .enableCrop(true)//是否开启裁剪
                .compress(true)//是否压缩
                .showCropFrame(true)// 是否显示裁剪矩形边框
                .withAspectRatio(1,1)//裁剪比例
                .previewImage(true)
                .previewEggs(true)//预览图片时是否增强左右滑动图片体验
                .forResult( ResultCode );
    }

    private void news_Createinsert_mysql(Context context) {
        new Thread( new Runnable() {
            @Override
            public void run() {
                try {
                    String user_id = "";
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection cn= getConnection( getString( R.string.mysql_address_utf8 )+"?useUnicode=true&characterEncoding=UTF-8",getString( R.string.mysql_username ),getString( R.string.mysql_password ));
                    System.out.println("连接数据库成功");
                    String sql="SELECT user_id FROM personals WHERE user_wx='"+user+"'";
                    Statement st=(Statement)cn.createStatement();
                    ResultSet rs=st.executeQuery(sql);
                    while(rs.next()){
                        user_id=rs.getString("user_id");
                    }
                    String temp_new_text=new_text.getText().toString(); //动态文字
                    String temp_new_url_text=new_url_text.getText().toString(); //动态链接文字
                    String temp_new_dz_text=new_dz_text.getText().toString(); //动态点赞人数
                    String temp_year=new_rq_text.getText().toString().split( "年" )[0]; //动态发布的年
                    String temp_month=new_rq_text.getText().toString().split( "年" )[1].split( "月" )[0];//动态发布的月
                    String temp_day=new_rq_text.getText().toString().split( "年" )[1].split( "月" )[1].split( "日" )[0];//动态发布的日
                    String temp_time=new_sj_text.getText().toString(); //动态发布时间
                    String temp_address=new_szwz_text.getText().toString(); //动态发布地点
                    /**
                     *
                     * 先判断类型，再选择是否上传至ftp
                     * 最后插入数据
                     */
                    if (pyq_type==1){

                        sql="INSERT INTO pyq VALUES("+user_id+",NULL,"+pyq_type+",'"+temp_new_text+"',NULL,NULL,NULL,"+temp_new_dz_text+","+temp_day+","+temp_month+","+temp_year+",'"+temp_time+"','"+temp_address+"')";
                    }else if (pyq_type==2){
                        //动态图片地址
                        for (int i=0;i<news_pictures_nums;i++){
                            if (!news_pictures_path[i].equals( "" )|!news_pictures_path[i].equals( "null" )|!news_pictures_path[i].equals( " " )){
                                sendImgae( new File( news_pictures_path[i] ) );
                                if (i==8){
                                    last_news_pictures_path=last_news_pictures_path+news_pictures_name[i];
                                }else{
                                    last_news_pictures_path=last_news_pictures_path+news_pictures_name[i]+",";
                                }
                            }
                        }
                        sql="INSERT INTO pyq VALUES("+user_id+",NULL,"+pyq_type+",'"+temp_new_text+"','"+last_news_pictures_path+"',NULL,NULL,"+temp_new_dz_text+","+temp_day+","+temp_month+","+temp_year+",'"+temp_time+"','"+temp_address+"')";
                    }else if (pyq_type==3){
                        //动态链接图片地址
                        sendImgae( new File( new_url_img_path) );
                        last_new_url_img_path=new_url_img_name;
                        sql="INSERT INTO pyq VALUES("+user_id+",NULL,"+pyq_type+",Null,NULL,'"+temp_new_url_text+"','"+last_new_url_img_path+"',"+temp_new_dz_text+","+temp_day+","+temp_month+","+temp_year+",'"+temp_time+"','"+temp_address+"')";
                    }else if (pyq_type==4){
                        //动态链接图片地址
                        sendImgae( new File( new_url_img_path) );
                        last_new_url_img_path=new_url_img_name;
                        sql="INSERT INTO pyq VALUES("+user_id+",NULL,"+pyq_type+",'"+temp_new_text+"',NULL,'"+temp_new_url_text+"','"+last_new_url_img_path+"',"+temp_new_dz_text+","+temp_day+","+temp_month+","+temp_year+",'"+temp_time+"','"+temp_address+"')";
                    }

                    if (st.executeUpdate( sql )==0){
                        Looper.prepare();
                        Toast.makeText( context,getString( R.string.error ),Toast.LENGTH_LONG ).show();
                        Looper.loop();
                    }else {
                        Looper.prepare();
                        Toast.makeText( context,getString( R.string.ok ),Toast.LENGTH_LONG ).show();
                        Looper.loop();
                    }
                    cn.close();
                    st.close();
                    rs.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } ).start();

    }
    /**
     *
     * 因各种原因，在此不设服务端来处理文件，而是通过ftp文件上传的形式来实现图片上传服务器
     * 后续在CSDN本人的博客(white_mvlog)中会写一遍Android端与服务器端是怎么进行数据交互（图片上传等）的
     *
     * @param localpicture
     */
    private void sendImgae(File localpicture) {
        new Thread( new Runnable() {
            @Override
            public void run() {
                FTPClient ftpClinet=new FTPClient();
                try {
                    /**
                     *
                     * 上传头像和朋友圈背景图片
                     */
                    ftpClinet.connect( getString( R.string.ftp_address ) );
                    ftpClinet.login( getString( R.string.ftp_username ),getString( R.string.ftp_password ) );
                    File file=new File( String.valueOf( localpicture ) );
                    // 设置中文编码集，防止中文乱码
                    ftpClinet.changeDirectory( getString( R.string.ftp_path ) );
                    ftpClinet.append( file );
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (FTPIllegalReplyException e) {
                    e.printStackTrace();
                } catch (FTPException e) {
                    e.printStackTrace();
                } catch (FTPAbortedException e) {
                    e.printStackTrace();
                } catch (FTPDataTransferException e) {
                    e.printStackTrace();
                }

            }
        } ).start();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data );
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 188:
                    // 结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult( data );
                    for (int i=0;i<selectList.size();i++){
                        ImageView roundedImageView=new ImageView(getApplicationContext());
                        roundedImageView.setImageURI( Uri.fromFile(new File(selectList.get( i ).getCompressPath())));
                        new_picture.addView( roundedImageView );
                        roundedImageView.setPadding( 0 ,15 ,15 ,0 );
                        AutoLinearLayout.LayoutParams params = (AutoLinearLayout.LayoutParams) roundedImageView
                                .getLayoutParams();
                        params.width=((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));;
                        params.height=((int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics()));;
                        roundedImageView.setLayoutParams( params );
                        roundedImageView.setId( i );
                        if (news_pictures_nums==5){
                            news_pictures_nums=5;
                        }else{
                            news_pictures_nums++;
                        }
                        news_pictures_path[i]=selectList.get( i ).getCompressPath();
                        int path_nums=selectList.get( i ).getCompressPath().split( "/" ).length;
                        news_pictures_name[i]=selectList.get( i ).getCompressPath().split( "/" )[path_nums-1];
//                        for (LocalMedia media : selectList) {
//                            if (media.isCompressed()){
//                                news_pictures_path[i]=media.getCompressPath();
//                                news_pictures_name[i]=media.getCompressPath().split( "/" ).length[9];
//                                System.out.println( "Num："+media.getCompressPath());
//                            }else {
//                                news_pictures_path[i]=selectList.get( i ).getPath();
//                                news_pictures_name[i]=selectList.get( i ).getFileName();
//                            }
//                        }


                        // 添加长按点击弹出选择菜单
                        roundedImageView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                            public void onCreateContextMenu(ContextMenu menu, View v,
                                                            ContextMenu.ContextMenuInfo menuInfo) {
                                roundedImageView.setVisibility( View.GONE );
                                new_picture.removeView( roundedImageView );
                                news_pictures_nums--;
                            }
                        });

                        System.out.println( "Num："+selectList.get( i ).getNum() );
                        System.out.println( "getFileName："+selectList.get( i ).getFileName() );
                        System.out.println( "getPath未压缩："+selectList.get( i ).getPath() );
                        System.out.println( "getPath压缩："+selectList.get( i ).getCompressPath() );
                        System.out.println( "getId："+selectList.get( i ).getId() );
                        System.out.println( "getSize："+selectList.get( i ).getSize() );
                        System.out.println( "getChooseModel："+selectList.get( i ).getChooseModel() );
                        System.out.println( "getWidth和getHeight："+selectList.get( i ).getWidth() +"   "+selectList.get( i ).getHeight());

                    }
                    new_picture.removeView( img_select );
                    new_picture.addView( img_select );
                    selectList.get( 0 ).getNum();
                    break;
                case 1:
                    // 结果回调
                    List<LocalMedia> selectList1 = PictureSelector.obtainMultipleResult( data );
                    new_url_img_path=selectList1.get( 0 ).getCompressPath();
                    int img_path_length=selectList1.get( 0 ).getCompressPath().split( "/" ).length;
                    new_url_img_name=selectList1.get( 0 ).getCompressPath().split( "/" )[img_path_length-1];
                    new_url_img.setImageURI( Uri.fromFile( new File(selectList1.get( 0 ).getCompressPath()) ) );
                    break;
                default:
                    break;
            }
        }
    }


}
